package logic

import (
	"context"
	"errors"
	"fmt"
	"order/cache"
	"order/models"
	"strconv"

	"order/orderrpc/internal/svc"
	"order/orderrpc/orderrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CarAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCarAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CarAddLogic {
	return &CarAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CarAddLogic) CarAdd(in *orderrpc.CarAddRequest) (*orderrpc.CarAddResponse, error) {
	// todo: add your logic here and delete this line
	var user models.User
	data, err := user.FindUserById(models.DB, in.UserId)
	if err != nil {
		return nil, err
	}
	if data.ID == 0 {
		return nil, errors.New("用户不存在")
	}
	var products models.Product
	product, err := products.FindProductById(models.DB, in.ProductId)
	if err != nil {
		return nil, err
	}
	if product.ID == 0 {
		return nil, errors.New("商品不存在")
	}
	exists, err := cache.CartProductExists(in.UserId, in.ProductId)
	if err != nil {
		return nil, err
	}
	if exists == 0 {
		MapData := map[string]interface{}{
			"productId": in.ProductId,
			"userId":    in.UserId,
			"number":    in.ProductNum,
			"title":     product.Title,
			"image":     product.Image,
			"price":     product.Price,
		}
		err = cache.CarAdd(in.UserId, in.ProductId, MapData)
		if err != nil {
			return nil, errors.New("购物车添加失败")
		}
	} else {
		err = cache.UpdateCartProductNumber(in.UserId, in.ProductId, in.ProductNum)
		if err != nil {
			return nil, err
		}
		key := fmt.Sprintf("cart:%d:%d", in.UserId, in.ProductId)
		cartProduct, _ := cache.FindCartProduct(key)
		number, _ := strconv.Atoi(cartProduct["number"])
		i := int64(number) + in.ProductNum
		if i < 0 {
			err = cache.CartProductDel(in.UserId, in.ProductId)
			if err != nil {
				return nil, err
			}
		} else {
			err = cache.UpdateCartProductNumber(in.UserId, in.ProductId, in.ProductNum)
			if err != nil {
				return nil, err
			}
		}
	}
	return &orderrpc.CarAddResponse{
		ProductId: int64(product.ID),
	}, nil
}
